package com.yc.bank.dao;

import com.yc.bank.entity.Account;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDao {

    /**
     *  OprecordDao 实现
     *      1. insert 方法  ==> 写账号操作流水
     *      2. selectByAid  ==> 查账号操作流水
     */

    @Resource
    JdbcTemplate jdbcTemplate;

    // 注册
    public void insert(String id, String pwd, double money){
        jdbcTemplate.update(
                "insert into bank_account values (?,?,?)",
                id, pwd, money);
    }

    // 存取款
    public void updateBalance(String id, double money){
        jdbcTemplate.update(
                "update bank_account set balance=balance+? where id=?",
                money , id);
    }

    public Account selectById(String id){
        String sql = "select * from bank_account where id=?";
        final ResultSetExtractor<Account> rse = new ResultSetExtractor<Account>() {
            @Override
            public Account extractData(ResultSet rs) throws SQLException, DataAccessException {
                rs.next();
                Account a = new Account();
                a.setId(rs.getString(1));
                a.setPwd(rs.getString(2));
                a.setBalance(rs.getDouble(3));
                return a;
            }
        };
        return jdbcTemplate.query(sql,rse, id);
    }

    public List<Account> selectAll(){
        String sql = "select * from bank_account";
        return jdbcTemplate.query(sql,(rs, index)->{
            Account a = new Account();
            a.setId(rs.getString(1));
            a.setPwd(rs.getString(2));
            a.setBalance(rs.getDouble(3));
            return a;
        });
    }

}
